<template>
  <div class="dialog-container">
    <el-dialog
      title="采购订单"
      :visible.sync="dialogVisible"
      width="70%"
      top="4%"
      :close-on-click-modal="false"
    >
      <!-- 第一行，信息 -->
      <el-card shadow="always">
        <el-form
          :inline="true"
          class="demo-form-inline"
          label-width="100px"
          size="small"
        >
          <el-form-item label="订单编号" style="margin-bottom: 0px">
            <el-input v-model="id" disabled />
          </el-form-item>
          <el-form-item label="订单日期" style="margin-bottom: 0px">
            <el-date-picker
              v-model="date"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              :disabled="!flag"
            />
          </el-form-item>
          <el-form-item style="margin: 0 0 0px 30px">
            <el-button
              v-if="flag"
              type="success"
              @click="addItem"
            >添加货物</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 第二行，表格详情 -->
      <el-card shadow="always" style="margin-top: 5px">
        <el-table
          style="width: 100%"
          :data="porders"
          size="small"
          height="240px"
        >
          <el-table-column type="index" width="30px" align="center" />
          <!-- 货物名称 -->
          <el-table-column label="货物名称" width="190" align="center">
            <template slot-scope="{ row, $index }">
              <el-select
                v-model="row.goodsId"
                placeholder="请选择"
                size="small"
                filterable
                :disabled="!flag"
                @change="getUnit(row, $index)"
              >
                <el-option
                  v-for="item in goods"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    v-for="label in item.labels"
                    :key="label.id"
                    style="float: right; color: #8492a6; font-size: 13px"
                  >{{ "（" + label.name + "）" }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <!-- 进货价格 -->
          <el-table-column
            label="进货价格"
            width="140"
            align="center"
          ><template slot-scope="{ row }">
            <el-input-number
              v-model="row.inPrice"
              name="sdf"
              :precision="2"
              :step="100.0"
              style="width: 130px"
              size="small"
              controls-position="right"
              :disabled="!flag"
            /> </template></el-table-column>

          <!-- 数量 -->
          <el-table-column
            label="数量"
            width="110"
            align="center"
          ><template slot-scope="{ row }">
            <el-input-number
              v-model="row.num"
              controls-position="right"
              :min="1"
              style="width: 90px"
              size="small"
              :disabled="!flag"
              @change="changeCount(row)"
            /> </template></el-table-column>

          <!-- 单位 -->
          <el-table-column
            label="单位"
            width="50"
            align="center"
          ><template slot-scope="{ row }">
            {{ row.unit }}
          </template></el-table-column>

          <!-- 供应商 -->
          <el-table-column
            label="供应商"
            width="190"
            align="center"
          ><template slot-scope="{ row }">
            <el-select
              v-model="row.supplierId"
              filterable
              placeholder="请选择"
              style="width: 180px"
              size="small"
              :disabled="!flag"
            >
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select> </template></el-table-column>

          <!-- 操作 -->
          <el-table-column v-if="flag" label="操作" align="center">
            <template slot-scope="{ $index }">
              <el-popconfirm
                :ref="`popover-${$index}`"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon="el-icon-info"
                title="确认要删除该条采购记录？"
                @onConfirm="deleteItem($index)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                />
              </el-popconfirm> </template></el-table-column>

          <!-- 状态 -->
          <el-table-column v-else label="状态" align="center">
            <template slot-scope="{ row }">
              <el-tag
                :type="
                  row.flag === 0
                    ? 'warning'
                    : row.flag === row.num
                      ? 'success'
                      : ''
                "
              >{{
                row.flag === 0
                  ? "待入库"
                  : row.flag === row.num
                    ? "已入库"
                    : "入库中"
              }}</el-tag>
            </template></el-table-column>
        </el-table>
      </el-card>
      <!-- 第三行，页脚插槽 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div></el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Dialog',
  data() {
    return {
      // 弹窗显示与隐藏
      dialogVisible: false,
      // 查看|添加模式标记
      flag: '',
      // 订单编号
      id: '',
      // 订单日期
      date: new Date(),
      // 订单信息
      porders: [],
      // 品牌-货物列表
      goods: [],
      // 供应商列表
      suppliers: []
    }
  },
  mounted() {
    this.getGoods()
    this.getSupplier()
  },
  methods: {
    // 修改货物数量
    changeCount(row) {
      console.log(row)
    },
    // 添加采购记录
    addItem() {
      // 构造采购记录对象
      const obj = {
        goodsId: '',
        inPrice: 0,
        num: 1,
        supplierId: '',
        unit: ''
      }
      // 将采购记录添加到列表中
      this.porders.push(obj)
    },
    // 删除采购记录
    deleteItem($index) {
      // splice可以删除数组中的元素，返回的是被删除的元素，且会改变原数组的值
      this.porders.splice($index, 1)
    },
    // 获取品牌-货物列表
    async getGoods() {
      const response = await this.$API.pOrder.getGoods()
      if (response.code === 200) {
        this.goods = response.data
      } else {
        this.$message.error('获取货物列表失败！')
      }
    },
    // 获取供应商列表
    async getSupplier() {
      const resposne = await this.$API.supplier.get()
      if (resposne.code === 200) {
        this.suppliers = resposne.data
      } else {
        this.$message.error('获取供应商列表失败！')
      }
    },
    // 获取货物单位
    async getUnit(row, $index) {
      const response = await this.$API.pOrder.getUnit(row.goodsId)
      if (response.code === 200) {
        // 修复动态修改表格数据后，数据不改变的bug
        // this.porders[$index].unit = response.data
        // 本来unit应该通过response.data.unit获取，但后端unit是Unit类型的，这里凑用String类型的name
        this.$set(row, 'unit', response.data.name)
        this.$set(row, 'inPrice', response.data.inPrice)
      } else {
        this.$message.error(response.msg)
      }
    },
    // 保存采购订单
    async add() {
      const response = await this.$API.pOrder.add(this.id, this.date, this.$store.state.user.id, this.porders)
      if (response.code === 200) {
        // 提醒采购订单创建成功
        this.$message.success(response.msg)
        // 通知父组件，重新拉取采购订单数据
        this.$emit('get')
        // 关闭弹窗
        this.dialogVisible = false
      } else {
        this.$message.error(response.msg)
      }
    }
  }
}
</script>

<style>
.el-form-item {
  margin-bottom: 22px;
}
</style>
